<?php
/**
 *
 */
function build_where( $filter ) {

	static $cond = array();
	
	if(count($filter)){
		foreach($filter as $type => $items ){
		
//			print "..." . $type . "<br>";
			switch ($type) {
				case 'items':
					if(count($items)){
						$first = true;
						foreach($items as $item) {
							if (!$first) {							
								$tmp = array_pop( $cond );
								$condition .= ' ' . $tmp . ' ';
								array_push($cond, $tmp);
							} else {
								$first = false;
							}
							$condition .= "( " . $item[field] . getCondition( $item[condition], mysql_escape_string($item[value]) ) . ")";
//							print "..." . $condition . "<br>";
						}
					}					
					
					array_pop( $cond );		
					return( '( ' . $condition . ' )' );
					break;
					
				case 'condition':
					array_push($cond, $items);
					break;
					
				case 'group':
					
					if(count($items)){
						$first = true;
						foreach($items as $item) {
							if (!$first) {
								$tmp = array_pop( $cond );
								$str .= ' ' . $tmp . ' ';
							} else {
								$first = false;
							}
							$str .= build_where($item);
						}
					}

					return( '( ' . $str . ' )' );					
					break;
			}
		}
	}	
}

/**
 *
 */
function build_order( $tokens ) {

	if(count($tokens)){
		$qq = array();
		foreach($tokens as $token) {
			$qq[] = $token['field'] . " " . $token['dir'];
		}

		return (' ORDER BY ' . implode(", ", $qq) );
	}

}

/**
 *
 */
function build_limit( $start = '', $range = '' ) {

	$str = " LIMIT ";
	if ($range != '') {
		if ($start !== '' && $start != NULL) {
			$str .= $start . ', ';
		}
		return ($str . $range);
	}
	
}

function getCondition($condition, $value){
	$str = "";
	switch($condition){
		case 'LIKE_RIGHT' : 
			$str = " LIKE '{$value}%' ";
			break;
		case 'LIKE_LEFT' : 
			$str = " LIKE '%{$value}' ";
			break;
		case 'LIKE_BOTH' : 
			$str = " LIKE '%{$value}%' ";
			break;
		case 'EQUAL' : 
			$str = " = '{$value}' ";
			break;
		case 'NOT_EQUAL' : 
			$str = " != '{$value}'";
			break;
		case 'IN' : 
			$str = " IN ({$value}) ";
			break;
		DEFAULT :
			$str = false;
	}
	return $str;
}

?>